/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csse3004.GD;

/**
 *
 * @author Tom McNair - S41758984
 */
import csse3004.GD.DA.LoginDA;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class LoginValidator implements Validator {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    public LoginValidator() {
        loginService = new LoginDA();
    }

    private LoginService loginService = new LoginDA();
    
    public boolean supports(Class clazz) {
        return Account.class.equals(clazz);
    }

    public void validate(Object obj, Errors errors) {
        Account loggy = (Account) obj;
        String username = loggy.getUsername();
        String password = loggy.getPassword();
        
        logger.info("Checking Empty String");
        logger.info(username);
        logger.info(password);
        System.out.println(username+password);
        if (username.equals("")) {
            errors.rejectValue("username", "error.not-specified", null, "Username Required.");
        }        else if ("".equals(password)) {
            errors.rejectValue("password", "error.not-specified", null, "Password Required.");
        } else {
            if(loginService.checkAccountDetails(username, password)){
                logger.info("Hazah!:" + username);
            } else {
                errors.rejectValue("username", "error.not-specified", null, "Invalid Credentials.");
            }
        }
    }    
}